package com.kob.backend.service.impl.record;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kob.backend.mapper.RecordMapper;
import com.kob.backend.mapper.UserMapper;
import com.kob.backend.pojo.Record;
import com.kob.backend.pojo.User;
import com.kob.backend.service.record.GetRecordListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
@Service
public class GetRecordListServiceImpl implements GetRecordListService {
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private UserMapper userMapper;//因为record表只记录了用户id，没有用户其他信息，所以要再通过userMapper查用户信息
    @Override
    public JSONObject getList(Integer page) {//通过这个接口，可以查看所有人的对局记录（每页10条，只看）
        IPage<Record> recordIPage = new Page<>(page, 10);//IPage是mybatis的API,传入页号和每页数
        QueryWrapper<Record> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");//所有记录，按id降序排序
        List<Record> records = recordMapper.selectPage(recordIPage, queryWrapper).getRecords();//传入页面信息和查询条件
        //这里只能查出第page页的所有记录
        //这样会先把记录按id降序排序，然后分页
        JSONObject resp = new JSONObject();//把下面的集合，封装到这个对象
        List<JSONObject> items = new LinkedList<>();//返回给前端的对象集合，每个对象，存一局记录
        for (Record record: records) {
            User userA = userMapper.selectById(record.getAId());//查到AB
            User userB = userMapper.selectById(record.getBId());
            JSONObject item = new JSONObject();//每局记录，存双方头像用户名结果，以及record表
            item.put("a_photo", userA.getPhoto());
            item.put("a_username", userA.getUsername());
            item.put("b_photo", userB.getPhoto());
            item.put("b_username", userB.getUsername());
            String result = "平局";//判断结果
            if ("A".equals(record.getLoser())) result = "B胜";
            else if ("B".equals(record.getLoser())) result = "A胜";
            item.put("result", result);
            item.put("record", record);
            items.add(item);
        }
        resp.put("records", items);//封装发送到前端
        resp.put("records_count", recordMapper.selectCount(null));//记录对局总数，方便前端写页面排版
        return resp;
    }
}
